package task;

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long time;
    public MyTimerTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}
class MyTimer{
    private Object locker = new Object();
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    public MyTimer(){
        Thread t = new Thread(() -> {
            while (true){
                synchronized (locker){
                    try {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask current = queue.peek();
                        if (System.currentTimeMillis() >= current.getTime()) {
                            current.run();
                            queue.poll();
                        } else {
                            locker.wait(current.getTime() - System.currentTimeMillis());
                        }
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();

    }
    public void schedule(Runnable runnable,long delay){
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}

public class Test9 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(() ->{
            System.out.println("3秒后执行");
        },3000);
        timer.schedule(() ->{
            System.out.println("2秒后执行");
        },2000);
        timer.schedule(() ->{
            System.out.println("1秒后执行");
        },1000);
    }
}
